import 'package:flutter/material.dart';
import 'package:flutter_wan_android/data/article/article_entity.dart';
import 'package:flutter_wan_android/feature/home/home_banner.dart';
import 'package:provider/provider.dart';

import '../article/article_details_screen.dart';
import 'home_view_model.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  late final HomeViewModel _viewModel;
  final ScrollController _scrollController = ScrollController();
  final GlobalKey<RefreshIndicatorState> _refreshKey = GlobalKey<RefreshIndicatorState>();

  @override
  void initState() {
    super.initState();
    _viewModel = context.read<HomeViewModel>();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController.removeListener(_onScroll);
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final articleList = context.select<HomeViewModel, List<ArticleEntity>>(
          (viewModel) => viewModel.articleList,
    );
    final listStatus = context.select<HomeViewModel, ListStatus>(
          (viewModel) => viewModel.listStatus,
    );
    return Scaffold(
      appBar: AppBar(title: Center(child: Text("首页"))),
      backgroundColor: Colors.white,
      body: RefreshIndicator(
        key: _refreshKey,
        onRefresh: _onRefresh,
        child: CustomScrollView(
          controller: _scrollController,
          slivers: [
            SliverToBoxAdapter(
              child: HomeBanner(),
            ),
            _buildContent(listStatus,articleList),
          ],

        ),
      ),
    );
  }

  Widget _buildContent(ListStatus listStatus,List<ArticleEntity> articleList) {

    if(listStatus is LIdle){
      return SliverToBoxAdapter();
    }else if(listStatus is LEmpty){
      return SliverToBoxAdapter(child: GestureDetector(onTap: (){
        if(mounted){
          _refreshKey.currentState?.show();
        }
      },child: Center(child: Text("空布局测试，点击重新加载"),),),);
    } else {
      return SliverList.builder(
        itemCount: articleList.length + 1,
        itemBuilder: (context, index) {
          if(index == articleList.length){
            if(listStatus is LCompleted){
              return Center(child: Text("没有更多数据了"));
            }else if(listStatus is LError){
              return Center(child: GestureDetector(onTap: (){
                debugPrint("列表出错重试");
                _viewModel.requestArticleList(false);
              },child: Text("加载出错，点击重试")));
            }else {
              return Center(child: SizedBox(width: 20,height: 20,child: CircularProgressIndicator()));
            }
          } else {
            final item = articleList[index];
            return InkWell(onTap: (){
              Navigator.push(context, MaterialPageRoute(builder: (context){
                return ArticleDetailsScreen(title: item.title,url: item.link,);
              }));
            },child: ListTile(title: Text(item.title)));
          }
        },
      );
    }
  }



  void _onScroll() {
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent &&
        _viewModel.listStatus is LSuccess) {
      _viewModel.requestArticleList(false);
    }
  }


  Future<void> _onRefresh() async {
    await Future.delayed(const Duration(seconds: 2));
    if (mounted) {
      _viewModel.requestBannerList();
      _viewModel.requestArticleList(true);
    }

  }
}
